<template>
  <div class="page-com">
    <!-- <basic-container> -->
    <avue-crud ref="crud" v-model="form" :option="option" :table-loading="loading" :data="data"
      :permission="permissionList" :page.sync="page" @search-change="searchChange" @search-reset="searchReset"
      @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
      @refresh-change="refreshChange" @on-load="onLoad">
      <template slot="goodsType" slot-scope="scope">
        <div>
          <el-tag v-if="scope.row.goodsType == 1" type="success">酒类</el-tag>
          <el-tag v-else-if="scope.row.goodsType != 1" type="info">酒类</el-tag>
        </div>
      </template>
      <template slot="status" slot-scope="scope">
        <div>
          <el-tag v-if="scope.row.status == 1" type="success">上架</el-tag>
          <el-tag v-else-if="scope.row.status == 0" type="info">下架</el-tag>
        </div>
      </template>
      <template slot="status" slot-scope="scope">
        <div>
          <el-tag v-if="scope.row.status == 1" type="success">上架</el-tag>
          <el-tag v-else-if="scope.row.status == 0" type="info">下架</el-tag>
        </div>
      </template>
      <template slot="goodsName" slot-scope="scope">
        <!-- <div class="ellipsis2 w150">
          {{ scope.row.goodsName }}
        </div> -->
        <span class="ellipsis2">{{ scope.row.goodsName }}</span>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" @click="add">新增</el-button>
      </template>
      <template slot="menu" slot-scope="scope">
        <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑
        </el-button>
        <el-button type="text" size="small" :class="[scope.row.status == 1 ? 'red' : 'green']"
          @click="changeStatus(scope.row)">
          {{ scope.row.status == 1 ? '下架' : '上架' }}
        </el-button>
      </template>
    </avue-crud>

    <el-dialog title="商品信息" center append-to-body :visible.sync="box" top="72px" width="500px">
      <div>
        <h3>商品信息</h3>
        <el-form v-if="box" ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="商品名称" prop="goodsName">
            <el-input v-model="ruleForm.goodsName" maxlength="30" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品分类" prop="categoryId">
            <el-select v-model="ruleForm.categoryId" style="width: 100%;" placeholder="请选择商品分类">
              <el-option v-for="item in categoryList" :label="item.categoryName" :value="item.categoryId" />
            </el-select>
          </el-form-item>
          <el-form-item label="商品专栏" prop="goodsSpecial">
            <el-select v-model="ruleForm.goodsSpecial" style="width: 100%;" placeholder="请选择商品专栏">
              <el-option v-for="item in goodsSpecialList" :label="item.dictValue" :value="Number(item.dictKey)" />
            </el-select>
          </el-form-item>
          <el-form-item label="会员价【A】" prop="memberPrice">
            <el-input-number v-model="ruleForm.memberPrice" :precision="2" style="width: 100%;" :min="0"
              placeholder="请输入商品的会员价" />
          </el-form-item>
          <el-form-item label="售卖价【B】" prop="salePrice">
            <el-input-number v-model="ruleForm.salePrice" :precision="2" style="width: 100%;" :min="0"
              placeholder="请输入商品的售卖价" />
          </el-form-item>
          <el-form-item label="指导价【C】" prop="guidePrice">
            <el-input-number v-model="ruleForm.guidePrice" :precision="2" style="width: 100%;" :min="0"
              placeholder="请输入商品的指导价" />
          </el-form-item>
          <el-form-item label="已售出数量" prop="saleNum">
            <el-input-number v-model="ruleForm.saleNum" :precision="2" style="width: 100%;" :min="0"
              placeholder="请输入已售出数量" />
          </el-form-item>
          <el-form-item label="产品类型" prop="goodsType">
            <el-select v-model="ruleForm.goodsType" style="width: 100%;" placeholder="请选择产品类型">
              <el-option v-for="item in goodsTypeList" :label="item.dictValue" :value="Number(item.dictKey)" />
            </el-select>
          </el-form-item>
          <el-form-item label="商品库存" prop="stockNum">
            <el-input-number v-model="ruleForm.stockNum" :precision="2" style="width: 100%;" :min="0"
              placeholder="请输入已售出数量" />
          </el-form-item>
          <div>
            <h3>其他信息</h3>
            <el-form-item label="实际销量">
              <span>{{ ruleForm.realSaleNum || 0 }}</span>
            </el-form-item>
          </div>

          <h3>商品图片</h3>

          <el-form-item label="商品缩略图" prop="thumbnailImage">
            <el-upload v-loading="loading1" :class="[ruleForm.thumbnailImage ? 'upload-more-disabled' : '']" action="#"
              :on-remove="() => ruleForm.thumbnailImage = ''" :http-request="selectPicUpload"
              accept=".jpg,.jpeg,.png,.gif" list-type="picture-card" :limit="1" :file-list="thumbnailImageList">
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
          <el-form-item label="商品详情图" prop="image">
            <el-upload v-loading="loading2" :class="[ruleForm.image ? 'upload-more-disabled' : '']" action="#"
              :on-remove="() => ruleForm.image = ''" :http-request="selectPicUpload2" accept=".jpg,.jpeg,.png,.gif"
              list-type="picture-card" :limit="1" :file-list="headImageList">
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
          <el-form-item label="产品介绍" prop="detailImageList">
            <el-upload v-loading="loading3" action="#"
              :class="[detailImageList && detailImageList.length >= 5 ? 'upload-more-disabled' : '']"
              :http-request="selectPicUpload3" :on-remove="remove3" accept=".jpg,.jpeg,.png,.gif" list-type="picture-card"
              :limit="5" :file-list="detailImageList">
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
          <el-form-item label="">
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" :loading="btnLoading" @click="submit">确定</el-button>
          </el-form-item>
        </el-form>

      </div>
    </el-dialog>

  </div>
</template>

<script>
import { goodsList, changeStatus, goodsCategoryList, addGoods, goodsInfo, updateGoods, getOrderList, getOrderGoodsDetails, updateOrderGoodsSendStatus } from '@/api/mallManage'
import { operationLogList, dict_biz } from '@/api/system/operation'
import { uploadImg } from '@/api/user'
import {
  getToken,
  getTokenName
} from '@/utils/auth'
export default {
  data() {
    return {
      form: {},
      box: false,
      showConfirm: false,
      props: {
        label: 'menuName',
        value: 'id'
      },
      menuGrantList: [],
      menuTreeObj: [],
      selectionList: [],
      expandedKeys: [],
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        rowKey: 'roleId',
        emptyBtnText: '重置',
        columnBtn: false,
        searchShowBtn: false,
        refreshBtn: false,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        cellBtn: false,
        tree: true,
        border: false,
        index: false,
        selection: false,
        viewBtn: false,
        dialogWidth: 500,
        dialogClickModal: false,
        menuWidth: 130,
        align: 'center',
        column: [
          {
            label: '商品名称',
            prop: 'goodsName',
            search: true,
            span: 24,
            labelWidth: 120

          },
          {
            label: '会员价【A】',
            prop: 'memberPrice',
            search: false,
            span: 24,
            labelWidth: 120
          },
          {
            label: '售卖价【B】',
            prop: 'salePrice',
            search: false,
            span: 24,
            labelWidth: 100,
            width: 100
          },
          {
            label: '指导价【C】',
            prop: 'guidePrice',
            search: false,
            span: 24,
            width: 100
          },
          {
            label: '产品类型',
            prop: 'goodsType',
            search: false,
            span: 24,
            labelWidth: 100,
            width: 100
          },
          {
            label: '产品缩略图',
            prop: 'thumbnailImage',
            search: false,
            span: 24,
            labelWidth: 100
          },
          {
            label: '状态',
            prop: 'status',
            search: false,
            span: 24,
            labelWidth: 100,
            width: 100
          },
          {
            label: '实际售出',
            prop: 'saleNum',
            search: false,
            span: 24,
            labelWidth: 100,
            width: 100
          },
          {
            label: '商品库存',
            prop: 'stockNum',
            search: false,
            span: 24,
            labelWidth: 100,
            width: 100
          },
          {
            label: '上传时间',
            prop: 'createTime',
            search: false,
            span: 24,
            labelWidth: 100,
            width: 140
          }
        ]
      },
      data: [],
      selectRoleId: '',
      detailMsg: {},
      isShowGoodsBtn: false, // 确认发货按钮
      rules: {
        detailImageList: [
          { required: true, message: '请上传产品介绍', trigger: ['change'] }
        ],
        image: [
          { required: true, message: '请上传商品详情图', trigger: ['blur', 'change'] }
        ],
        thumbnailImage: [
          { required: true, message: '请上传商品缩略图', trigger: ['blur', 'change'] }
        ],
        stockNum: [
          { required: true, message: '请填写商品库存', trigger: ['blur', 'change'] }
        ],
        goodsType: [
          { required: true, message: '请选择产品类型', trigger: ['blur', 'change'] }
        ],
        saleNum: [
          { required: true, message: '请填写已售出数量', trigger: ['blur', 'change'] }
        ],
        memberPrice: [
          { required: true, message: '请填写会员价【A】', trigger: ['blur', 'change'] }
        ],
        salePrice: [
          { required: true, message: '请填写售卖价【B】', trigger: ['blur', 'change'] }
        ],
        guidePrice: [
          { required: true, message: '请填写指导价【C】', trigger: ['blur', 'change'] }
        ],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: ['blur', 'change'] }
        ],
        goodsSpecial: [
          { required: true, message: '请选择商品专栏', trigger: ['blur', 'change'] }
        ],
        goodsName: [
          { required: true, message: '请填写商品名称', trigger: ['blur', 'change'] }
        ]
      },
      ruleForm: {
        'categoryId': '',
        'detailImageList': [],
        'goodsId': '',
        'goodsName': '',
        'goodsSpecial': '',
        'goodsType': 1,
        'guidePrice': 0,
        'image': '',
        'memberPrice': 0,
        'saleNum': 0,
        'salePrice': 0,
        'stockNum': 0,
        'thumbnailImage': ''
      },
      btnLoading: false,
      categoryList: [],
      goodsSpecialList: [],
      goodsTypeList: [],
      requireLink: process.env.VUE_APP_BASE_API + '/system/oss/putFile',
      thumbnailImageList: [],
      headImageList: [],
      detailImageList: [],
      loading1: false,
      loading2: false,
      loading3: false
    }
  },
  computed: {
    permissionList() {
      return {
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtn: false
      }
    },
    ids() {
      const ids = []
      this.selectionList.forEach((ele) => {
        ids.push(ele.roleId)
      })
      return ids
    }
  },
  watch: {},
  mounted() {
    this.getGoodsCategoryList()
    this.getdictbiz()
    // this.initData();
  },
  methods: {
    add() {
      this.box = true
      this.ruleForm = {
        'categoryId': '',
        'detailImageList': [],
        'goodsId': '',
        'goodsName': '',
        'goodsSpecial': '',
        'goodsType': 1,
        'guidePrice': 0,
        'image': '',
        'memberPrice': 0,
        'saleNum': 0,
        'salePrice': 0,
        'stockNum': 0,
        'thumbnailImage': ''
      }
      this.thumbnailImageList = []
      this.headImageList = []
      this.detailImageList = []
    },
    // 缩略图
    selectPicUpload(obj) {
      const formData = new FormData()
      formData.append('file', obj.file)
      this.loading1 = true
      uploadImg(formData, undefined).then((res) => {
        this.$message({
          message: '上传成功',
          type: 'success'
        })
        this.ruleForm.thumbnailImage = res.data.link
        this.loading1 = false
      }).catch(err => {
        this.loading1 = false
      })
    },
    // 详情图
    selectPicUpload2(obj) {
      const formData = new FormData()
      formData.append('file', obj.file)
      this.loading2 = true
      uploadImg(formData, undefined).then((res) => {
        this.$message({
          message: '上传成功',
          type: 'success'
        })
        this.ruleForm.image = res.data.link
        this.loading2 = false
      }).catch(err => {
        this.loading2 = false
      })
    },
    // 产品介绍
    selectPicUpload3(obj) {
      console.log(obj)
      const formData = new FormData()
      formData.append('file', obj.file)
      this.loading3 = true
      uploadImg(formData, undefined).then((res) => {
        this.$message({
          message: '上传成功',
          type: 'success'
        })
        this.detailImageList.push({
          name: obj.file.name,
          url: res.data.link
        })
        this.loading3 = false
      }).catch(err => {
        this.loading3 = false
      })
    },
    remove3(file, fileList) {
      console.log(file, fileList, this.detailImageList, this.ruleForm.detailImageList)
      this.detailImageList = this.detailImageList.filter(item => item.uid !== file.uid)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    getdictbiz() {
      dict_biz('goods_special,goods_type').then((res) => {
        console.log('查看res', res)
        if (res.code === 200) {
          this.goodsSpecialList = res.data.goods_special
          this.goodsTypeList = res.data.goods_type
        }
      })
    },
    // 上下架
    async changeStatus(row) {
      // this.$confirm(`确定要${row.status === 1 ? '下架' : '上架'}商品?`, {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     return changeStatus({
      //       goodsId: row.goodsId
      //     })
      //   })
      //   .then(() => {
      //     this.onLoad(this.page)
      //     this.$message({
      //       type: 'success',
      //       message: '操作成功!'
      //     })
      //     this.$refs.crud.toggleSelection()
      //   })
      const result = await changeStatus({
        goodsId: row.goodsId
      })
      if (result.code === 200) {
        this.onLoad(this.page)
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
      }
    },
    async getGoodsCategoryList() {
      const result = await goodsCategoryList({})
      if (result.code === 200) {
        this.categoryList = result.data
      }
    },

    openshowConfirm() {
      if (this.detailMsg.orderType === 2 && this.detailMsg.orderSendStatus === 2) {
        this.ruleForm.logisticsCode = this.detailMsg.logisticsCode
      } else {
        this.ruleForm.logisticsCode = ''
      }
      this.showConfirm = true
    },
    closeDialog() {
      this.box = false
    },
    async handleEdit(row) {
      // this.isShowGoodsBtn = false
      // const result = await getOrderGoodsDetails({
      //   'logisticsCode': row.logisticsCode,
      //   'orderCode': row.orderCode
      // })
      // if (result.code === 200) {
      //   this.detailMsg = result.data
      //   this.box = true
      // }
      console.log(row)
      const result = await goodsInfo({
        goodsId: row.goodsId
      })
      if (result.code === 200 && result.data) {
        this.ruleForm = result.data
      } else {
        this.ruleForm = { ...row }
        this.ruleForm.detailImageList = row.detailImage ? JSON.parse(row.detailImage) : []
      }
      this.thumbnailImageList = row.thumbnailImage ? [{ name: '缩略图', url: row.thumbnailImage }] : []
      this.headImageList = row.image ? [{ name: '缩略图', url: row.image }] : []
      this.detailImageList = (this.ruleForm.detailImageList.length) ? this.ruleForm.detailImageList.map((v, i) => {
        return {
          name: i,
          url: v
        }
      }) : []
      this.detailImageList = this.detailImageList.filter(Boolean)
      // thumbnailImageList: [],
      // headImageList: [],
      // detailImageList: []
      this.box = true
      console.log('this.ruleForm', this.ruleForm, this.detailImageList)
    },
    submit() {
      this.ruleForm.detailImageList = this.detailImageList.map(v => v.url)
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.btnLoading = true
          const params = JSON.parse(JSON.stringify(this.ruleForm))
          console.log('params', params, this.detailImageList)
          params.detailImageList = this.detailImageList.map(v => v.url)
          const RequestFn = params.goodsId ? updateGoods : addGoods
          RequestFn(params).then(res => {
            if (res.code === 200) {
              this.$message.success(`${params.goodsId ? '修改' : '新增'}成功`)
              this.btnLoading = false
              setTimeout(() => {
                this.box = false
                this.showConfirm = false
                this.searchReset()
              })
            }
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    searchReset() {
      this.query = {}
      this.onLoad(this.page)
    },
    searchChange(params, done) {
      this.query = params
      this.page.currentPage = 1
      this.onLoad(this.page, params)
      done()
    },
    selectionChange(list) {
      this.selectionList = list
    },
    selectionClear() {
      this.selectionList = []
      this.$refs.crud.toggleSelection()
    },

    async handleRole(row) {
      await this.handleEdit(row)
      this.isShowGoodsBtn = true
    },
    copy(content) {
      // 创建输入框元素
      const input = document.createElement('input')// 不会保留文本格式
      // 如果要保留文本格式，比如保留换行符，或者多行文本，可以使用  textarea 标签，再配和模板字符串 ` `
      // const input = document.createElement('textarea')
      // 将想要复制的值
      input.value = content
      // 页面底部追加输入框
      document.body.appendChild(input)
      // 选中输入框
      input.select()
      // 执行浏览器复制命令
      document.execCommand('Copy')
      // 弹出复制成功信息
      // this.$message.success('复制成功');
      // 复制后移除输入框
      input.remove()
      this.$message.success('复制成功')
    },

    // handleDelete() {
    //   // if (this.selectionList.length === 0) {
    //   //   this.$message.warning('请选择至少一条数据')
    //   //   return
    //   // }
    //   this.$confirm('确定将选择数据删除?', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       return remove(this.ids)
    //     })
    //     .then(() => {
    //       this.onLoad(this.page)
    //       this.$message({
    //         type: 'success',
    //         message: '操作成功!'
    //       })
    //       this.$refs.crud.toggleSelection()
    //     })
    // },
    currentChange(currentPage) {
      this.page.currentPage = currentPage
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    refreshChange() {
      this.onLoad(this.page, this.query)
    },
    onLoad(page, params = {}) {
      this.loading = true
      goodsList({
        current: page.currentPage,
        size: page.pageSize,
        ...Object.assign(params, this.query)
      }).then((res) => {
        const data = res.data
        this.data = data.records
        this.page.total = data.total
        this.loading = false
        this.selectionClear()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page-com {
  padding: 20px;
}

.menuGrantList {
  max-height: 380px;
  overflow: auto;
}

.detail-box {
  color: #3e3e3e;
}

.desc {
  color: #666;
}

.copy {
  display: inline-block;
  padding: 4px 8px;
  background-color: #eee;
  cursor: pointer;
  border-radius: 4px;
}

.flex {
  display: flex;
}

.flex-col {
  flex-direction: column;
}

.flex-between {
  justify-content: space-between;
}

.item-price {
  margin-left: auto;
}

.price {
  color: #CF2222;
}

.old-price {
  text-decoration: line-through;
  color: #A1A1A1;
  font-size: 10px;
}

.red {
  color: #CF2222;
}

.green {
  color: #67c23a;
}

.w150 {
  width: 150px;
}

.ellipsis2 {
  display: -webkit-box;
  text-overflow: ellipsis;
  overflow: hidden;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

//隐藏图片上传框的css
.upload-more-disabled {
  ::v-deep .el-upload {
    display: none;
  }
}
</style>
